package com.sk.ccflower.server.lib.sockUtils.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import org.apache.log4j.Logger;


public class BaseNioSock{

	protected Logger log;
	protected Selector selector;
	protected SocketChannel sc;

	public BaseNioSock(){
		this.log = Logger.getLogger(getClass());
	}

	protected void register(SelectableChannel ch , int ops) throws ClosedChannelException , IOException{
		if( ch == null ) {
			//this.log.info("Invalid connection.");
			System.out.println("Invalid connection.");
			return;
		}
		if( ch.isOpen() ){
			ch.configureBlocking(false);
			ch.register(this.selector , ops);
		}else{
			throw new IOException("channel is not open.");
		}
	}

	public void start(){
		SelectionKey sKey = null;
		while(true){
			try{
				this.selector.select();

				for( Iterator<?> it = this.selector.selectedKeys().iterator() ; it.hasNext();){
					sKey = (SelectionKey)it.next();
					it.remove();
					if( sKey.isAcceptable() ){
						//this.accept(sKey);
					}else if( sKey.isReadable() ) {
						this.read(sKey);
					}
				}

			} catch( IOException ex ){
				//this.log.error(ex.toString() , ex);
				ex.printStackTrace();
			}
		}
	}


	private void read(SelectionKey sKey){
		SocketChannel sc = null;

		byte[] b = null;
		int total = 0;
		int size = 0 ;
		StringBuffer sb = new StringBuffer();
		try{
			sc = (SocketChannel)sKey.channel();
			ByteBuffer buff = ByteBuffer.allocate(30);

			while( total < 1000 ){
				size=sc.read( buff );
				total += size;
				if( size<0 ){
					//this.log.error("read buff size < 0 ");
					System.out.println( "read buff size < 0 " );
					throw new IOException( "read buff size < 0" );
				}
				buff.flip();
				b=new byte[size];
				buff.get( b );
				buff.clear();

				//this.log.debug("MSG=[" + new String(b) + "]");
				System.out.println( total + "::::::::::rece="+new String( b ) );
				sb.append(new String( b ));
			}
			this.send( sc , sb.toString());


		} catch( IOException ex ){
			//this.log.error(ex.toString() , ex);
			ex.printStackTrace();
			try{
				if( sc != null ) {
					sc.close();
					System.out.println( "sc close" );
				}
			} catch( IOException ex2 ){
			}

		} finally{

		}

	}

	public void send(SocketChannel sc , String msg) throws IOException{
		ByteBuffer buff=ByteBuffer.allocate( 1024 );
		byte[] b = msg.getBytes();
			buff.put( b );
			buff.flip();
			sc.write( buff );
			System.out.println( "write="+msg );
	}

}
